<template>
  <view class="container">
    <!-- 导航栏 -->
    <uni-nav-bar 
      dark 
      :fixed="true" 
      shadow 
      status-bar 
      left-icon="arrow-left" 
      title="客户经理看板" 
      @clickLeft="back" 
    />
    
    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 表格容器 -->
      <view class="table-container" :style="{ height: tableHeight }">
        <view class="table-scroll-container">
          <view class="data-table">
            <!-- 表头 -->
            <view class="table-header table-header-fixed">
              <!-- 客户名称列 -->
              <view class="table-cell cell-city table-col-fixed-1" @click="handleSort('jlName')">
                <view class="header-content">
                  <text >客户经理名称</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" 
                      :style="{color: sortConfig.key === 'jlName' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">
                      ▲
                    </text>
                    <text class="sort-icon down-icon"
                      :style="{color: sortConfig.key === 'jlName' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">
                      ▼
                    </text>
                  </view>
                </view>
              </view>
              
              <!-- 合计列 -->
              <view class="table-cell cell-data" @click="handleSort('hj')">
                <view class="header-content">
                  <text>合计</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" 
                      :style="{color: sortConfig.key === 'hj' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">
                      ▲
                    </text>
                    <text class="sort-icon down-icon"
                      :style="{color: sortConfig.key === 'hj' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">
                      ▼
                    </text>
                  </view>
                </view>
              </view>
              
              <!-- 逾期欠费列 -->
              <view class="table-cell cell-data" @click="handleSort('yqqf')">
                <view class="header-content">
                  <text>逾期欠费</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" 
                      :style="{color: sortConfig.key === 'yqqf' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">
                      ▲
                    </text>
                    <text class="sort-icon down-icon"
                      :style="{color: sortConfig.key === 'yqqf' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">
                      ▼
                    </text>
                  </view>
                </view>
              </view>
              
              <!-- 所属专业列 -->
              <view class="table-cell cell-data" @click="handleSort('dataSource')">
                <view class="header-content">
                  <text>所属专业</text>
                  <view class="sort-icon-group">
                    <text class="sort-icon up-icon" 
                      :style="{color: sortConfig.key === 'dataSource' && sortConfig.type === 'asc' ? '#ff0101' : '#999'}">
                      ▲
                    </text>
                    <text class="sort-icon down-icon"
                      :style="{color: sortConfig.key === 'dataSource' && sortConfig.type === 'desc' ? '#ff0101' : '#999'}">
                      ▼
                    </text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 表格内容区 -->
            <view class="table-body">
              <!-- 数据行 -->
              <view 
                class="table-row" 
                v-for="(item, index) in sortedTableData" 
                :key="'data-' + index + item.khCode + item.rq"
                :class="index % 2 === 0 ? 'row-even' : 'row-odd'"
              >
                <view class="table-cell cell-city table-col-fixed-1 customer-name" style="justify-content: center;">
                  {{ item.jlName }}
                </view>
                <view class="table-cell cell-data">{{ item.hj }}</view>
                <view class="table-cell cell-data">{{ item.yqqf }}</view>
                <view class="table-cell cell-data">
                  {{ item.dataSource === 'jd' ? '寄递' : item.dataSource === 'yw' ? '邮务' : item.dataSource }}
                </view>
              </view>
              
              <!-- 空白填充行 -->
              <view 
                class="table-row empty-row" 
                v-for="index in emptyRowCount" 
                :key="'empty-' + index"
                :class="(sortedTableData.length + index) % 2 === 0 ? 'row-even' : 'row-odd'"
              >
                <view class="table-cell cell-city table-col-fixed-1"></view>
                <view class="table-cell cell-data"></view>
                <view class="table-cell cell-data"></view>
                <view class="table-cell cell-data"></view>
              </view>
              
              <!-- 合计行 -->
              <view class="table-row total-tr table-row-total">
                <view class="table-cell cell-city table-col-fixed-1 total-fixed-col">合计</view>
                <view class="table-cell cell-data">{{ total.HJ }}</view>
                <view class="table-cell cell-data">{{ total.YQQF }}</view>
                <view class="table-cell cell-data"></view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 分页按钮区域 -->
      <view class="pagination-wrapper">
        <!-- 分页信息显示 -->
        <view class="pagination-info">
          <text>共 {{ pageInfo.total || 0 }} 条记录 | 第 {{ currentPage }} / {{ pageInfo.pageTotal || 0 }} 页</text>
        </view>
        
        <!-- 分页按钮组 -->
        <view class="pagination-buttons">
          <!-- 首页按钮 -->
          <button 
            class="page-btn first-btn" 
            @click="handleFirstPage"
            :disabled="currentPage <= 1"
          >
            首页
          </button>
          
          <!-- 上一页按钮 -->
          <button 
            class="page-btn prev-btn" 
            @click="handlePrevPage"
            :disabled="currentPage <= 1"
          >
            上一页
          </button>
          
          <!-- 下一页按钮 -->
          <button 
            class="page-btn next-btn" 
            @click="handleNextPage"
            :disabled="currentPage >= pageInfo.pageTotal"
          >
            下一页
          </button>
          
          <!-- 尾页按钮 -->
          <button 
            class="page-btn last-btn" 
            @click="handleLastPage"
            :disabled="currentPage >= pageInfo.pageTotal"
          >
            尾页
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import store from '../../common/store.js'
import utils from '../../common/utils'

export default {
  data() {
    return {
      tableData: [],
      // 分离当前页码和后端返回的分页信息，避免引用问题
      currentPage: 1,  // 单独存储当前页码，用于页面展示和计算
      pageInfo: {
        total: 0,      // 总记录数
        pageTotal: 0,  // 总页数
        pageSize: 10   // 每页条数
      },
      userId: '',
      total: { HJ: '', YQQF: '' },
      rq: '',
      sortConfig: {
        key: '',
        type: 'asc'
      },
      minRowCount: 10,
      tableHeight: 'calc(100% - 120px)'
    };
  },
  computed: {
    sortedTableData() {
      const data = [...this.tableData];
      if (!this.sortConfig.key) return data;
      
      return data.sort((a, b) => {
        const valueA = a[this.sortConfig.key];
        const valueB = b[this.sortConfig.key];
        
        if (typeof valueA === 'number' && typeof valueB === 'number') {
          return this.sortConfig.type === 'asc' ? valueA - valueB : valueB - valueA;
        }
        
        if (typeof valueA === 'string' && typeof valueB === 'string') {
          const compare = valueA.localeCompare(valueB, 'zh-CN');
          return this.sortConfig.type === 'asc' ? compare : -compare;
        }
        
        return 0;
      });
    },
    emptyRowCount() {
      const need = this.minRowCount - this.sortedTableData.length;
      return need > 0 ? need : 0;
    }
  },
  onLoad() {
    this.calculateTableHeight();
    uni.onWindowResize(this.calculateTableHeight);
  },
  onUnload() {
    uni.offWindowResize(this.calculateTableHeight);
  },
  onShow() {
    console.info("用户信息：" + JSON.stringify(uni.getStorageSync("userInfo")));
    // 页面显示时使用当前页码加载数据
    this.initPage(this.currentPage);
  },
  methods: {
    back() {
      // 跳转至khzf页面（请替换为实际路径）
      uni.switchTab({
        url: '/pages/index/index',
        fail: (err) => {
          // 若不是TabBar页面，使用redirectTo
          uni.redirectTo({
            url: '/pages/index/index',
            fail: (err2) => {
              console.error('跳转index页面失败：', err2);
              // 降级为返回上一页
              this.handleBack();
            }
          });
        }
      });
    },
    handleSort(key) {
      if (this.sortConfig.key === key) {
        this.sortConfig.type = this.sortConfig.type === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortConfig.key = key;
        this.sortConfig.type = 'asc';
      }
    },
    calculateTableHeight() {
      const { windowHeight } = uni.getSystemInfoSync();
      const navHeight = 44;
      const paginationHeight = 70;
      this.tableHeight = `${windowHeight - navHeight - paginationHeight}px`;
    },
    // 初始化/刷新页面数据，接收页码参数
    initPage: async function (pageNum) {
      // 显示加载中
      this.$utils.showLoading("数据加载中...");
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        
        // 打印当前请求的页码，用于调试
        console.log("请求页码：", pageNum);
        
        // 加密参数中明确传递当前要请求的页码
        const enData = this.$utils.encrypt(
          JSON.stringify({ 
            timestamp,
            curpage: pageNum,       // 明确使用传入的页码
            pagesize: 30
          }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        
        const res = await this.$myRequest.post_token(
          getApp().globalData.khjlkbInit,
          { data: enData + "" }
        );
        
        this.$utils.hideLoading();
        if (res.code === 200) {
          const decryptedData = JSON.parse(utils.decrypt(
            res.data,
            userInfo.aesKey,
            userInfo.aesIv
          ));
          
          // 更新表格数据
          this.tableData = decryptedData.khjlqfSummaryListInfo?.listInfo || [];
          
          // 更新分页信息（从后端获取）
          this.pageInfo = {
            total: decryptedData.khjlqfSummaryListInfo?.pageInfo?.total || 0,
            pageTotal: decryptedData.khjlqfSummaryListInfo?.pageInfo?.pageTotal || 0,
            pageSize: decryptedData.khjlqfSummaryListInfo?.pageInfo?.pageSize || 10
          };
          
          // 更新当前页码（确保与请求的页码一致）
          this.currentPage = pageNum;
          
          // 更新合计数据
          this.total = decryptedData.hjList?.[0] || { HJ: '', YQQF: '' };
          this.rq = decryptedData.rq || '';
          
          // 调试信息
          console.log("当前页码更新为：", this.currentPage);
          console.log("后端返回总页数：", this.pageInfo.pageTotal);
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
        }
      } catch (e) {  
        this.$utils.hideLoading();
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);           
      }
    },
    
    // 首页逻辑
    handleFirstPage() {
      if (this.currentPage <= 1) return;
      // 直接传递1作为页码
      this.initPage(1);
    },
    
    // 上一页逻辑
    handlePrevPage() {
      if (this.currentPage <= 1) return;
      // 计算上一页页码并传递
      this.initPage(this.currentPage - 1);
    },
    
    // 下一页逻辑
    handleNextPage() {
      if (this.currentPage >= this.pageInfo.pageTotal) return;
      // 计算下一页页码并传递
      this.initPage(this.currentPage + 1);
    },
    
    // 尾页逻辑
    handleLastPage() {
      if (this.currentPage >= this.pageInfo.pageTotal || this.pageInfo.pageTotal === 0) return;
      // 直接传递总页数作为页码
      this.initPage(this.pageInfo.pageTotal);
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.sort-icon-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1px;
  margin-left: 6px;
}

.sort-icon {
  font-size: 11px;
  line-height: 1;
  transition: color 0.2s ease;
  display: inline-block;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/* 主容器 */
.container {
  width: 100%;
  height: 100vh;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  width: 100%;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  transition: height 0.3s ease;
  overflow: hidden;
}

.table-scroll-container {
  flex: 1;
  overflow: auto;
  position: relative;
  -webkit-overflow-scrolling: touch;
}

.data-table {
  width: 100%;
  min-width: 600px;
  box-sizing: border-box;
}

.table-header {
  display: flex;
  background-color: #f8f8f8;
  color: #333;
  font-weight: 500;
  height: auto;
  min-height: 48px;
}

.table-header-fixed {
  position: sticky;
  top: 0;
  z-index: 20;
}

.table-body {
  display: flex;
  flex-direction: column;
}

/* 表格行样式 */
.table-row {
  display: flex;
  width: 100%;
  height: auto;
  min-height: 48px;
}

.row-even {
  background-color: #ffffff;
}
.row-odd {
  background-color: #fee8ea;
}

/* 表格单元格基础样式 */
.table-cell {
  padding: 8px;
  text-align: center;
  font-size: 14px;
  border-right: 1px solid #eee;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  cursor: pointer;
}

/* 客户名称列特殊样式 */
.cell-city { 
  width: 180px;
}

.customer-name {
  justify-content: flex-start;
  padding-left: 10px;
  white-space: normal;
  word-break: break-word;
  text-align: left;
}

.cell-data { flex: 1; min-width: 120px; }

.table-header .table-cell:active {
  background-color: #eaeaea;
}

.table-cell:last-child {
  border-right: none;
}

.table-col-fixed-1 {
  position: sticky;
  left: 0;
  z-index: 10;
  background-color: #f8f8f8;
}

.row-even .table-col-fixed-1 {
  background-color: #ffffff;
}
.row-odd .table-col-fixed-1 {
  background-color: #fee8ea;
}

.table-row-total {
  position: sticky;
  bottom: 0;
  z-index: 15;
}
.total-tr {
  background-color: #ff0101 !important;
  color: #fff !important;
  font-weight: bold;
}
.total-tr .table-cell {
  color: #fff !important;
  border-right: 1px solid rgba(255,255,255,0.3);
  border-bottom: none;
  padding: 8px;
}
.total-fixed-col {
  background-color: #ff0101 !important;
  z-index: 16;
  justify-content: center !important;
}

.empty-row .table-cell {
  background-color: transparent !important;
}

/* 分页区域样式 */
.pagination-wrapper {
  width: 100%;
  height: 70px;
  padding: 10px 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-top: 1px solid #eee;
  background-color: #f9f9f9;
}

.pagination-info {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  text-align: center;
}

.pagination-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.page-btn {
  width: 80px;
  height: 36px;
  line-height: 36px;
  padding: 0;
  margin: 0;
  font-size: 14px;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #ddd;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 禁用状态样式 */
.page-btn:disabled {
  background-color: #f5f5f5;
  color: #999;
  border-color: #e0e0e0;
  cursor: not-allowed;
}

.page-btn:not(:disabled):active {
  background-color: #f0f0f0;
}

/* 滚动条样式 */
.table-scroll-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.table-scroll-container::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}
</style>
